package com.talkweb.historylib.provider;

import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.app.Context;

import java.util.HashMap;

/**
 * @author SUQI
 * @date 2021/1/29
 * @description
 **/
public class ViewHolder {
    private HashMap<Integer, Component> mComponents;
    private Component mConvertComponent;
    private Context mContext;

    private ViewHolder(Context context, Component itemView) {
        this.mContext = context;
        this.mConvertComponent = itemView;
        this.mComponents = new HashMap<>();
    }

    public static ViewHolder createViewHolder(Context context, ComponentContainer parent, int layoutId) {
        Component itemView = LayoutScatter.getInstance(context).parse(layoutId, parent, false);
        return new ViewHolder(context, itemView);
    }

    /**
     * 根据资源id获取控件并存储
     *
     * @param viewId
     * @param <T>
     * @return
     */
    public <T extends Component> T getView(int viewId) {
        Component view = (Component) this.mComponents.get(viewId);
        if (view == null) {
            view = mConvertComponent.findComponentById(viewId);
            mComponents.put(viewId, view);
        }
        return (T) view;
    }

    /**
     * 获取当前itemView
     *
     * @return
     */
    public Component getConvertComponent() {
        return mConvertComponent;
    }
}
